<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ECJTU 学生成绩分析系统 - 电子班牌版</title>
    <script src="chart.js"></script>
    <script src="axios.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }

        /* 登录模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            backdrop-filter: blur(5px);
        }

        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.15);
            padding: 40px;
            width: 90%;
            max-width: 450px;
            text-align: center;
            overflow: hidden;
        }

        .modal-content::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 5px;
            background: linear-gradient(90deg, #667eea, #764ba2);
        }

        .logo {
            margin-bottom: 30px;
        }

        .logo h1 {
            color: #667eea;
            font-size: 2.2rem;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .logo p {
            color: #666;
            font-size: 1rem;
        }

        .form-group {
            margin-bottom: 20px;
            text-align: left;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }

        .form-group input {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 10px;
            font-size: 1rem;
            transition: all 0.3s ease;
            background: #f8f9fa;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
            background: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .login-btn {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 20px;
        }

        .login-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .login-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .loading {
            display: none;
            text-align: center;
            margin: 20px 0;
        }

        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .message {
            display: none;
            padding: 12px;
            border-radius: 8px;
            margin: 15px 0;
            text-align: center;
        }

        .message.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .message.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* 主页面样式 */
        .navbar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .navbar .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .navbar h1 {
            font-size: 1.8rem;
            font-weight: 700;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .logout-btn {
            background: rgba(255,255,255,0.2);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .logout-btn:hover {
            background: rgba(255,255,255,0.3);
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .welcome-section {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }

        .welcome-section h2 {
            color: #667eea;
            margin-bottom: 10px;
            font-size: 1.5rem;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            transition: transform 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
        }

        .stat-card .number {
            font-size: 2rem;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }

        .stat-card .label {
            color: #666;
            font-size: 0.9rem;
        }

        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 25px;
            margin-bottom: 30px;
        }

        .card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }

        .card h3 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.3rem;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }

        .chart-container {
            position: relative;
            height: 300px;
            margin-top: 20px;
        }

        .scores-section {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }

        .semester-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .semester-tab {
            padding: 8px 16px;
            border: 2px solid #e1e5e9;
            background: white;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 0.9rem;
        }

        .semester-tab:hover {
            border-color: #667eea;
            color: #667eea;
        }

        .semester-tab.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .courses-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 15px;
        }

        .course-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            border-left: 4px solid #667eea;
        }

        .course-name {
            font-weight: 600;
            margin-bottom: 8px;
            color: #333;
        }

        .course-details {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.9rem;
            color: #666;
        }

        .course-grade {
            font-weight: bold;
            padding: 4px 8px;
            border-radius: 4px;
        }

        .course-grade.excellent {
            background: #d4edda;
            color: #155724;
        }

        .course-grade.good {
            background: #cce5ff;
            color: #004085;
        }

        .course-grade.average {
            background: #fff3cd;
            color: #856404;
        }

        .course-grade.poor {
            background: #f8d7da;
            color: #721c24;
        }

        .analysis-section {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }

        .analysis-section h4 {
            color: #667eea;
            margin-bottom: 15px;
            font-size: 1.2rem;
            border-bottom: 2px solid #667eea;
            padding-bottom: 8px;
        }

        .analysis-section ul {
            list-style-type: none;
            padding-left: 0;
        }

        .analysis-section li {
            padding: 8px 0;
            border-bottom: 1px solid #eee;
            position: relative;
            padding-left: 20px;
        }

        .analysis-section li::before {
            content: '•';
            position: absolute;
            left: 0;
            color: #667eea;
            font-weight: bold;
        }

        .error {
            background-color: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 8px;
            border: 1px solid #f5c6cb;
            margin: 20px 0;
        }

        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }

            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }

            .courses-grid {
                grid-template-columns: 1fr;
            }

            .navbar .container {
                flex-direction: column;
                gap: 10px;
            }

            .modal-content {
                margin: 20px;
                padding: 30px 25px;
            }
        }
    </style>
</head>
<body>
    <!-- 登录模态框 -->
    <div id="loginModal" class="modal">
        <div class="modal-content">
            <div class="logo">
                <h1>ECJTU</h1>
                <p>学生成绩智能分析系统</p>
            </div>

            <form id="loginForm">
                <div class="form-group">
                    <label for="studentId">学号</label>
                    <input type="text" id="studentId" name="studentId" placeholder="请输入您的学号" required>
                </div>

                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" name="password" placeholder="请输入您的密码" required>
                </div>

                <button type="submit" class="login-btn" id="loginBtn">
                    登录系统
                </button>
            </form>

            <div class="loading" id="loading">
                <div class="loading-spinner"></div>
                <p>正在登录并分析成绩...</p>
            </div>

            <div class="message" id="message"></div>
        </div>
    </div>

    <!-- 主页面内容 -->
    <nav class="navbar">
        <div class="container">
            <h1>ECJTU 学生成绩分析系统</h1>
            <div class="user-info">
                <span id="studentInfo">学号: 未登录</span>
                <button class="logout-btn" onclick="logout()">退出登录</button>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="welcome-section">
            <h2>欢迎使用成绩分析系统！</h2>
            <p id="welcomeText">请先登录以查看您的成绩数据和分析报告。</p>
        </div>

        <div class="stats-grid" id="statsGrid" style="display: none;">
            <div class="stat-card">
                <div class="number" id="totalCourses">-</div>
                <div class="label">总课程数</div>
            </div>
            <div class="stat-card">
                <div class="number" id="totalCredits">-</div>
                <div class="label">总学分</div>
            </div>
            <div class="stat-card">
                <div class="number" id="currentGPA">-</div>
                <div class="label">当前GPA</div>
            </div>
            <div class="stat-card">
                <div class="number" id="totalSemesters">-</div>
                <div class="label">学期数</div>
            </div>
        </div>

        <div class="main-content" id="mainContent" style="display: none;">
            <div class="card">
                <h3>📈 成绩趋势</h3>
                <div class="chart-container">
                    <canvas id="trendChart"></canvas>
                </div>
            </div>

            <div class="card">
                <h3>🎯 学科分布</h3>
                <div class="chart-container">
                    <canvas id="subjectChart"></canvas>
                </div>
            </div>
        </div>

        <div class="scores-section" id="scoresSection" style="display: none;">
            <h3>📚 学期成绩详情</h3>
            <div class="semester-tabs" id="semesterTabs">
                <!-- 学期标签将在这里动态生成 -->
            </div>
            <div class="courses-grid" id="coursesGrid">
                <!-- 课程卡片将在这里动态生成 -->
            </div>
        </div>

        <div class="analysis-section" id="analysisSection" style="display: none;">
            <h3>🤖 AI 智能分析报告</h3>
            <div id="analysisLoading" style="text-align: center; padding: 20px;">
                <div class="loading-spinner" style="margin: 0 auto 15px;"></div>
                <p>AI正在分析您的成绩数据，请稍候...</p>
            </div>
            <div id="analysisContent" style="display: none;">
                <!-- AI分析内容将在这里动态生成 -->
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let scoresData = null;
        let analysisData = null;
        let currentSemester = null;
        let trendChart = null;
        let subjectChart = null;
        let isLoggedIn = false;

        // 页面加载时检查登录状态
        document.addEventListener('DOMContentLoaded', function() {
            checkLoginStatus();
        });

        function checkLoginStatus() {
            // 检查是否已登录（通过尝试获取成绩数据）
            axios.get('/api/scores')
                .then(response => {
                    if (response.data.success) {
                        isLoggedIn = true;
                        hideLoginModal();
                        loadStudentData();
                    } else {
                        showLoginModal();
                    }
                })
                .catch(error => {
                    showLoginModal();
                });
        }

        function showLoginModal() {
            document.getElementById('loginModal').style.display = 'block';
        }

        function hideLoginModal() {
            document.getElementById('loginModal').style.display = 'none';
        }

        // 登录表单处理
        document.getElementById('loginForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const studentId = document.getElementById('studentId').value;
            const password = document.getElementById('password').value;
            const loginBtn = document.getElementById('loginBtn');
            const loading = document.getElementById('loading');
            const message = document.getElementById('message');
            
            if (!studentId || !password) {
                showMessage('请填写完整的学号和密码', 'error');
                return;
            }
            
            // 显示加载状态
            loginBtn.disabled = true;
            loginBtn.textContent = '登录中...';
            loading.style.display = 'block';
            message.style.display = 'none';
            
            try {
                // 发送登录请求
                const response = await fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        student_id: studentId,
                        password: password
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showMessage('登录成功！正在加载数据...', 'success');
                    isLoggedIn = true;
                    
                    // 延迟隐藏模态框并加载数据
                    setTimeout(() => {
                        hideLoginModal();
                        loadStudentData();
                    }, 1500);
                } else {
                    showMessage(result.message || '登录失败，请检查学号和密码', 'error');
                }
            } catch (error) {
                showMessage('网络错误，请稍后重试', 'error');
                console.error('Login error:', error);
            } finally {
                loginBtn.disabled = false;
                loginBtn.textContent = '登录系统';
                loading.style.display = 'none';
            }
        });

        function showMessage(text, type) {
            const message = document.getElementById('message');
            message.textContent = text;
            message.className = `message ${type}`;
            message.style.display = 'block';
        }

        async function loadStudentData() {
            try {
                document.getElementById('welcomeText').textContent = '正在加载您的成绩数据，请稍候...';
                
                // 获取成绩数据
                await loadScoresData();
                
                // 使用成绩数据中的学号信息更新界面
                if (scoresData && scoresData.success) {
                    document.getElementById('studentInfo').textContent = `学号: ${scoresData.student_id}`;
                    document.getElementById('welcomeText').textContent = 'AI正在分析您的成绩数据，请稍候...';
                }
                
                // 获取AI分析
                await loadAIAnalysis();
                
            } catch (error) {
                console.error('加载数据失败:', error);
                showError('数据加载失败，请刷新页面重试');
            }
        }

        async function loadScoresData() {
            try {
                const response = await axios.get('/api/scores');
                scoresData = response.data;
                
                if (scoresData.success) {
                    updateStats();
                    createSemesterTabs();
                    createCharts();
                    
                    // 显示相关区域
                    document.getElementById('statsGrid').style.display = 'grid';
                    document.getElementById('mainContent').style.display = 'grid';
                    document.getElementById('scoresSection').style.display = 'block';
                    document.getElementById('analysisSection').style.display = 'block';
                } else {
                    showError(scoresData.message);
                }
            } catch (error) {
                showError('获取成绩数据失败：' + error.message);
            }
        }

        async function loadAIAnalysis() {
            try {
                // 如果已有成绩数据，通过POST传递避免重复调用
                let response;
                if (scoresData && scoresData.success) {
                    response = await axios.post('/api/analyze', {
                        scores_data: scoresData
                    });
                    console.log('使用已缓存的成绩数据进行AI分析');
                } else {
                    // 兜底方案：使用GET请求
                    response = await axios.get('/api/analyze');
                }
                analysisData = response.data;
                
                document.getElementById('analysisLoading').style.display = 'none';
                
                // 更新欢迎信息状态
                const welcomeText = document.getElementById('welcomeText');
                if (welcomeText) {
                    welcomeText.textContent = 'AI成绩分析已完成，您可以查看下方的详细分析报告。';
                }
                
                if (analysisData.success) {
                    displayAIAnalysis();
                } else {
                    showError(analysisData.message);
                    if (welcomeText) {
                        welcomeText.textContent = 'AI分析遇到问题，请稍后重试。';
                    }
                }
            } catch (error) {
                document.getElementById('analysisLoading').style.display = 'none';
                const welcomeText = document.getElementById('welcomeText');
                if (welcomeText) {
                    welcomeText.textContent = 'AI分析遇到问题，请稍后重试。';
                }
                showError('AI分析失败：' + error.message);
            }
        }

        function updateStats() {
            if (!scoresData) return;
            
            const data = scoresData.data;
            let totalCourses = 0;
            let totalCredits = 0;
            
            Object.values(data).forEach(semester => {
                totalCourses += semester.course_count;
                semester.courses.forEach(course => {
                    totalCredits += course.credit;
                });
            });
            
            document.getElementById('totalCourses').textContent = totalCourses;
            document.getElementById('totalCredits').textContent = totalCredits;
            document.getElementById('currentGPA').textContent = scoresData.GPA || '未获取';
            document.getElementById('totalSemesters').textContent = scoresData.total_semesters;
        }

        function createSemesterTabs() {
            if (!scoresData) return;
            
            const tabsContainer = document.getElementById('semesterTabs');
            const semesters = Object.keys(scoresData.data).sort();
            
            tabsContainer.innerHTML = '';
            
            semesters.forEach((semester, index) => {
                const tab = document.createElement('button');
                tab.className = 'semester-tab';
                tab.textContent = `${semester} 学期`;
                tab.onclick = () => showSemesterCourses(semester);
                
                if (index === semesters.length - 1) {
                    tab.classList.add('active');
                    currentSemester = semester;
                }
                
                tabsContainer.appendChild(tab);
            });
            
            // 显示最新学期的课程
            if (currentSemester) {
                showSemesterCourses(currentSemester);
            }
        }

        function showSemesterCourses(semester) {
            currentSemester = semester;
            
            // 更新标签状态
            document.querySelectorAll('.semester-tab').forEach(tab => {
                tab.classList.remove('active');
                if (tab.textContent.includes(semester)) {
                    tab.classList.add('active');
                }
            });
            
            // 显示课程
            const coursesContainer = document.getElementById('coursesGrid');
            const semesterData = scoresData.data[semester];
            
            coursesContainer.innerHTML = '';
            
            semesterData.courses.forEach(course => {
                const courseCard = document.createElement('div');
                courseCard.className = 'course-card';
                
                const courseName = course.course_name.replace(/【.*?】/, ''); // 移除课程代码
                const gradeClass = getGradeClass(course.grade);
                
                courseCard.innerHTML = `
                    <div class="course-name">${courseName}</div>
                    <div class="course-details">
                        <span>${course.course_nature} | ${course.credit} 学分</span>
                        <span class="course-grade ${gradeClass}">${course.grade}</span>
                    </div>
                `;
                
                coursesContainer.appendChild(courseCard);
            });
        }

        function getGradeClass(grade) {
            const numGrade = parseFloat(grade);
            if (isNaN(numGrade)) {
                if (grade === '优秀') return 'excellent';
                if (grade === '良好') return 'good';
                if (grade === '合格') return 'average';
                return 'poor';
            }
            
            if (numGrade >= 90) return 'excellent';
            if (numGrade >= 80) return 'good';
            if (numGrade >= 70) return 'average';
            return 'poor';
        }

        function createCharts() {
            if (!scoresData) return;
            
            createTrendChart();
            createSubjectChart();
        }

        function createTrendChart() {
            const ctx = document.getElementById('trendChart').getContext('2d');
            const semesters = Object.keys(scoresData.data).sort();
            const averages = semesters.map(semester => {
                const courses = scoresData.data[semester].courses;
                const validGrades = courses.map(course => parseGrade(course.grade)).filter(g => g > 0);
                return validGrades.length > 0 ? validGrades.reduce((a, b) => a + b) / validGrades.length : 0;
            });
            
            if (trendChart) {
                trendChart.destroy();
            }
            
            trendChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: semesters,
                    datasets: [{
                        label: '学期平均分',
                        data: averages,
                        borderColor: '#667eea',
                        backgroundColor: 'rgba(102, 126, 234, 0.1)',
                        tension: 0.4,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: false,
                            min: 60,
                            max: 100
                        }
                    }
                }
            });
        }

        function createSubjectChart() {
            const ctx = document.getElementById('subjectChart').getContext('2d');
            const subjectTypes = {};
            
            Object.values(scoresData.data).forEach(semester => {
                semester.courses.forEach(course => {
                    const type = course.course_nature;
                    if (!subjectTypes[type]) {
                        subjectTypes[type] = [];
                    }
                    subjectTypes[type].push(parseGrade(course.grade));
                });
            });
            
            const labels = Object.keys(subjectTypes);
            const data = labels.map(type => {
                const grades = subjectTypes[type].filter(g => g > 0);
                return grades.length > 0 ? grades.reduce((a, b) => a + b) / grades.length : 0;
            });
            
            if (subjectChart) {
                subjectChart.destroy();
            }
            
            subjectChart = new Chart(ctx, {
                type: 'radar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '平均成绩',
                        data: data,
                        borderColor: '#667eea',
                        backgroundColor: 'rgba(102, 126, 234, 0.2)',
                        pointBackgroundColor: '#667eea'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        r: {
                            beginAtZero: false,
                            min: 60,
                            max: 100
                        }
                    }
                }
            });
        }

        function parseGrade(grade) {
            const numGrade = parseFloat(grade);
            if (!isNaN(numGrade)) return numGrade;
            
            switch(grade) {
                case '优秀': return 90;
                case '良好': return 75;
                case '合格': return 60;
                default: return 0;
            }
        }

        function displayAIAnalysis() {
            if (!analysisData || !analysisData.analysis) return;
            
            const content = document.getElementById('analysisContent');
            const analysis = analysisData.analysis;
            
            content.innerHTML = `
                <div class="analysis-section">
                    <h4>总体评估</h4>
                    <p><strong>GPA:</strong> ${analysis.overallAssessment.gpa}</p>
                    <p><strong>等级:</strong> ${analysis.overallAssessment.level}</p>
                    <p>${analysis.overallAssessment.summary}</p>
                </div>
                
                <div class="analysis-section">
                    <h4>学习优势</h4>
                    <ul>
                        ${analysis.performanceAnalysis.strengths.map(strength => `<li>${strength}</li>`).join('')}
                    </ul>
                </div>
                
                <div class="analysis-section">
                    <h4>改进建议</h4>
                    <ul>
                        ${analysis.performanceAnalysis.areasForImprovement.map(area => `<li>${area}</li>`).join('')}
                    </ul>
                </div>
                
                <div class="analysis-section">
                    <h4>学习趋势</h4>
                    <p><strong>趋势:</strong> ${analysis.learningTrajectory.trend}</p>
                    <p>${analysis.learningTrajectory.analysis}</p>
                </div>
                
                <div class="analysis-section">
                    <h4>个性化建议</h4>
                    <p><strong>学术建议:</strong></p>
                    <ul>
                        ${analysis.personalizedSuggestions.academic.map(suggestion => `<li>${suggestion}</li>`).join('')}
                    </ul>
                    <p><strong>发展建议:</strong></p>
                    <ul>
                        ${analysis.personalizedSuggestions.developmental.map(suggestion => `<li>${suggestion}</li>`).join('')}
                    </ul>
                </div>
            `;
            
            content.style.display = 'block';
        }

        function showError(message) {
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error';
            errorDiv.textContent = message;
            document.querySelector('.container').insertBefore(errorDiv, document.querySelector('.container').firstChild);
        }

        function logout() {
            // 清除数据
            scoresData = null;
            analysisData = null;
            isLoggedIn = false;
            
            // 隐藏所有内容区域
            document.getElementById('statsGrid').style.display = 'none';
            document.getElementById('mainContent').style.display = 'none';
            document.getElementById('scoresSection').style.display = 'none';
            document.getElementById('analysisSection').style.display = 'none';
            
            // 重置欢迎信息
            document.getElementById('studentInfo').textContent = '学号: 未登录';
            document.getElementById('welcomeText').textContent = '请先登录以查看您的成绩数据和分析报告。';
            
            // 清除表单
            document.getElementById('loginForm').reset();
            
            // 发送退出登录请求
            fetch('/logout')
                .then(() => {
                    showLoginModal();
                })
                .catch(() => {
                    showLoginModal();
                });
        }
    </script>
</body>
</html>